//
//  WJWMainTabBar.swift
//  SwiftWeibo
//
//  Created by 万嘉伟 on 16/7/18.
//  Copyright © 2016年 万嘉伟. All rights reserved.
 ///



/********************高亮状态以及添加中间发微博的加号**************************/
import UIKit

class WJWMainTabBar: UITabBar {

//闭包属性
    var composeCallback:(()->Void)?
    //懒加载按钮
    lazy var composeButton:UIButton = {
        let button = UIButton(type: UIButtonType.Custom)
        //按钮图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        //按钮背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
    
        //添加按钮上去
        self.addSubview(button)
        //点击事件
        button.addTarget(self, action: "composeClick", forControlEvents:UIControlEvents.TouchUpInside)
        
            return button
    }()
    
    // 按钮数量
    let itemCount: Int = 5
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 计算每个按钮的宽度
        let newItemWidth = self.frame.width / CGFloat(itemCount)
        // 遍历所有的item
        var index = 0
        for item in self.subviews {
            //UITabBarButton 类型,才需要设置frame
            //[UITabBarButton class]
            let cls = NSClassFromString("UITabBarButton")!
            if item.isKindOfClass(cls) {
//                print("item: \(item)")
            
                //重设item的frame
                item.frame = CGRect(x: CGFloat(index) * newItemWidth, y: 0, width: newItemWidth, height: self.frame.height)
                
                index++
                // 当是第2个以后,在往后移动一个
                if index == 2 {
                    index++
                }
            }
        }
        
        // 设置
        composeButton.frame = CGRect(x: 2 * newItemWidth, y: 0, width: newItemWidth, height: self.frame.height)
    }
    
    // MARK: - 按钮点击事件
    func composeClick() {
                print("composeClick")
        // View不能Modal出控制器
        composeCallback?()
    }

}
